<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">修改邮箱</text>
      </view>
      <view class="nav-right"></view>
    </view>
    
    <!-- 内容区域 -->
    <view class="content">
      <view class="form-card">
        <text class="form-title">修改绑定邮箱</text>
        <text class="form-desc">当前邮箱：{{ currentEmail }}</text>
        
        <view class="form-group">
          <text class="form-label">新邮箱地址</text>
          <view class="input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入新邮箱地址"
              v-model="formData.newEmail"
              @input="validateNewEmail"
            />
            <text class="input-icon">📧</text>
          </view>
          <text class="error-text" v-if="errors.newEmail">{{ errors.newEmail }}</text>
        </view>
        
        <view class="form-group">
          <text class="form-label">验证码</text>
          <view class="input-wrapper code-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入验证码"
              v-model="formData.code"
              maxlength="6"
              @input="validateCode"
            />
            <button 
              class="code-btn" 
              :disabled="codeSending || countdown > 0 || !formData.newEmail || !!errors.newEmail"
              @click="sendCode"
            >
              {{ codeButtonText }}
            </button>
          </view>
          <text class="error-text" v-if="errors.code">{{ errors.code }}</text>
          <text class="help-text">验证码将发送到新邮箱</text>
        </view>
        
        <view class="form-group">
          <text class="form-label">登录密码</text>
          <view class="input-wrapper">
            <input 
              class="form-input" 
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入登录密码以确认身份"
              v-model="formData.password"
              @input="validatePassword"
            />
            <text class="input-icon" @click="togglePassword">
              {{ showPassword ? '👁️' : '🔒' }}
            </text>
          </view>
          <text class="error-text" v-if="errors.password">{{ errors.password }}</text>
        </view>
        
        <button 
          class="submit-btn" 
          :disabled="!isFormValid || submitting"
          @click="handleSubmit"
        >
          {{ submitting ? '提交中...' : '确认修改' }}
        </button>
        
        <view class="tips">
          <text class="tips-title">💡 温馨提示</text>
          <text class="tips-item">• 修改邮箱后，新邮箱将作为您的登录账号</text>
          <text class="tips-item">• 请确保新邮箱地址真实有效</text>
          <text class="tips-item">• 验证码将发送到新邮箱地址</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import authService from '../../services/auth.js'
import { backToProfile } from '../../utils/navigation.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      currentEmail: '',
      
      formData: {
        newEmail: '',
        code: '',
        password: ''
      },
      
      errors: {
        newEmail: '',
        code: '',
        password: ''
      },
      
      // 验证码相关
      codeSending: false,
      countdown: 0,
      countdownTimer: null,
      
      // 提交状态
      submitting: false,
      
      // 密码显示控制
      showPassword: false
    }
  },
  
  computed: {
    codeButtonText() {
      if (this.codeSending) return '发送中...'
      if (this.countdown > 0) return `${this.countdown}秒`
      return '获取验证码'
    },
    
    isFormValid() {
      return this.formData.newEmail &&
             this.formData.code &&
             this.formData.code.length === 6 &&
             this.formData.password &&
             !this.errors.newEmail &&
             !this.errors.code &&
             !this.errors.password
    }
  },
  
  onLoad() {
    this.getStatusBarHeight()
    this.loadUserInfo()
  },
  
  onUnload() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  },
  
  methods: {
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
    },
    
    loadUserInfo() {
      const userInfo = authService.getLocalUserInfo()
      if (userInfo && userInfo.email) {
        this.currentEmail = userInfo.email
      } else {
        this.currentEmail = '未设置'
      }
    },
    
    goBack() {
      backToProfile()
    },
    
    // 表单验证
    validateNewEmail() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!this.formData.newEmail) {
        this.errors.newEmail = '请输入新邮箱地址'
      } else if (!emailRegex.test(this.formData.newEmail)) {
        this.errors.newEmail = '请输入正确的邮箱格式'
      } else if (this.formData.newEmail === this.currentEmail) {
        this.errors.newEmail = '新邮箱不能与当前邮箱相同'
      } else {
        this.errors.newEmail = ''
      }
    },
    
    validateCode() {
      if (!this.formData.code) {
        this.errors.code = '请输入验证码'
      } else if (this.formData.code.length !== 6) {
        this.errors.code = '验证码为6位数字'
      } else {
        this.errors.code = ''
      }
    },
    
    validatePassword() {
      if (!this.formData.password) {
        this.errors.password = '请输入登录密码'
      } else if (this.formData.password.length < 6) {
        this.errors.password = '密码至少6位'
      } else {
        this.errors.password = ''
      }
    },
    
    // 发送验证码
    async sendCode() {
      this.validateNewEmail()
      if (this.errors.newEmail) return
      
      this.codeSending = true
      
      try {
        console.log('📧 发送验证码到新邮箱:', this.formData.newEmail)
        
        // 调用后端接口发送验证码到新邮箱
        await authService.sendEmailCode({
          email: this.formData.newEmail,
          type: 'change_email'
        })
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        
        // 开始倒计时
        this.countdown = 60
        this.countdownTimer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(this.countdownTimer)
          }
        }, 1000)
        
      } catch (error) {
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      } finally {
        this.codeSending = false
      }
    },
    
    // 密码显示切换
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    
    // 提交修改
    async handleSubmit() {
      // 验证所有字段
      this.validateNewEmail()
      this.validateCode()
      this.validatePassword()
      
      if (!this.isFormValid) return
      
      this.submitting = true
      
      try {
        console.log('🔄 修改邮箱')
        
        // 调用后端接口修改邮箱
        const response = await authService.changeEmail({
          newEmail: this.formData.newEmail,
          code: this.formData.code,
          password: this.formData.password
        })
        
        uni.showToast({
          title: '邮箱修改成功',
          icon: 'success',
          duration: 1500
        })
        
        // 更新本地用户信息
        if (response.data) {
          uni.setStorageSync('user_info', response.data)
        }
        
        // 1.5秒后返回个人中心
        setTimeout(() => {
          backToProfile()
        }, 1500)
        
      } catch (error) {
        console.error('修改邮箱失败:', error)
        uni.showToast({
          title: error.message || '修改失败',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 1000;
}

.top-nav {
  position: fixed;
  top: var(--status-bar-height, 20px);
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  z-index: 999;
  
  .nav-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .back-icon {
      font-size: 40rpx;
      color: #333;
      font-weight: bold;
    }
  }
  
  .nav-center {
    flex: 1;
    text-align: center;
    
    .nav-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .nav-right {
    width: 60rpx;
  }
}

.content {
  padding: calc(var(--status-bar-height, 20px) + 88rpx + 40rpx) 40rpx 40rpx;
}

.form-card {
  background: #fff;
  border-radius: 32rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
  
  .form-title {
    font-size: 40rpx;
    font-weight: 700;
    color: #333;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .form-desc {
    font-size: 26rpx;
    color: #999;
    display: block;
    margin-bottom: 50rpx;
  }
  
  .form-group {
    margin-bottom: 40rpx;
    
    .form-label {
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      display: block;
      margin-bottom: 20rpx;
    }
    
    .input-wrapper {
      position: relative;
      
      .form-input {
        width: 100%;
        height: 90rpx;
        background: #f8f8f8;
        border-radius: 16rpx;
        padding: 0 90rpx 0 30rpx;
        font-size: 28rpx;
        color: #333;
        border: 2rpx solid transparent;
        transition: all 0.3s ease;
        box-sizing: border-box;
        
        &:focus {
          background: #fff;
          border-color: #667eea;
        }
      }
      
      .input-icon {
        position: absolute;
        right: 30rpx;
        top: 50%;
        transform: translateY(-50%);
        font-size: 36rpx;
      }
      
      &.code-wrapper {
        .form-input {
          padding-right: 210rpx;
        }
        
        .code-btn {
          position: absolute;
          right: 10rpx;
          top: 50%;
          transform: translateY(-50%);
          width: 180rpx;
          height: 70rpx;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #fff;
          font-size: 24rpx;
          border-radius: 12rpx;
          border: none;
          
          &::after {
            border: none;
          }
          
          &[disabled] {
            background: #ddd;
            color: #999;
          }
        }
      }
    }
    
    .error-text {
      font-size: 22rpx;
      color: #ff4757;
      display: block;
      margin-top: 12rpx;
      padding-left: 10rpx;
    }
    
    .help-text {
      font-size: 22rpx;
      color: #999;
      display: block;
      margin-top: 12rpx;
      padding-left: 10rpx;
    }
  }
  
  .submit-btn {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;
    border-radius: 16rpx;
    border: none;
    margin-top: 20rpx;
    
    &::after {
      border: none;
    }
    
    &[disabled] {
      background: #ddd;
      color: #999;
    }
  }
  
  .tips {
    margin-top: 50rpx;
    padding: 30rpx;
    background: #f8f9fa;
    border-radius: 16rpx;
    
    .tips-title {
      font-size: 26rpx;
      color: #333;
      font-weight: 600;
      display: block;
      margin-bottom: 20rpx;
    }
    
    .tips-item {
      font-size: 24rpx;
      color: #666;
      line-height: 2;
      display: block;
    }
  }
}
</style>


